package com.my.screenadapter.mThread;



import androidx.annotation.NonNull;

import org.apache.log4j.Logger;

import java.util.Map;
import java.util.Set;

/**
 * Created by ${张英杰} on 2019/1/18.
 *
 */
public class WatchDogCommonThread extends Thread{
    Logger logger = Logger.getLogger(WatchDogCommonThread.class);
    final Object mFeedWaiter = new Object();
    final int mTimeout;
    boolean mFeeded = false;
    Boolean mFound = false;
    String mThreadName;
    private WatchDogInterface mWatchDogInterface;


    public WatchDogCommonThread(@NonNull String threadName, int timeout, @NonNull WatchDogInterface watchDogInterface) {
        super("WatchDog_"+threadName);
        mThreadName = threadName;
        mTimeout = timeout;
        mWatchDogInterface = watchDogInterface;
    }

    @Override
    public void run() {
        while (true) {
            try {
                synchronized (mFeedWaiter) {
                    mFeedWaiter.wait(mTimeout);
                    if (mFeeded) {
                        mFeeded = false;
                        continue;
                    }
                }
                    Map<Thread, StackTraceElement[]> stacks = Thread.getAllStackTraces();
                    Set<Thread> set = stacks.keySet();
                    for (Thread key : set) {
                        if (mThreadName.equals(key.getName())) {
                            mFound = true;
                            break;
                        }
                    }

                    if (mFound) {
                        mFound = false;
                        continue;
                    }
                    logger.warn("Thread ( " + mThreadName + " ) not found, start it");
                if (mWatchDogInterface != null) {
                    mWatchDogInterface.callNoThread(mThreadName);
                }
            } catch (InterruptedException e) {
                logger.warn("WatchDog thread interrupted");
            }
        }
    }

    public synchronized void feed() {
        synchronized (mFeedWaiter) {
            mFeeded = true;
            mFeedWaiter.notify();
        }
    }

    //通知被观察线程 没了
    interface WatchDogInterface{
        void callNoThread(String str);
    }
}
